package com.cloudptt.api.comm;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.cloudptt.api.product.log.Log;
import com.cloudptt.api.product.upload.ZipListener;
import com.mcptt.db.model.SessionInfo;

import android.graphics.Bitmap;
import android.os.Environment;

public class FileOperation {

	private static final String THIS_FILE = "FileOperation";
	public static void deletExcessFile(File dir)
	{
		Log.d(THIS_FILE, "deletExcessFile dir = " + dir.toString());
		File[] fileArr = dir.listFiles( new FilenameFilter(){
			@Override
			public boolean accept(File dir,String fname){
				return !fname.contains( "-" );
			}
		});
		if(fileArr == null
				|| fileArr.length <= 10)
		{
			return;
		}
		Log.d( THIS_FILE, "listFiles: " + fileArr.toString( ) );
		Arrays.sort(fileArr, new Comparator<File>() {
			public int compare(File f1, File f2) {
				long diff = f1.lastModified() - f2.lastModified();
				if (diff > 0)
					return 1;
				else if (diff == 0)
					return 0;
				else
					return -1;
			}
			public boolean equals(Object obj) {
				return true;
			}
		});

		for(int i = 0; i < fileArr.length - 10; i ++)
		{
			File file = fileArr[i];
			Log.d(THIS_FILE, "deletExcessFile file = " + file.toString());
			boolean isSuc = file.delete();
			Log.d(THIS_FILE, "deletExcessFile result = " + isSuc);
		}
	}

	public static int KeyType_None = 0;
	public static int KeyType_Start = 1;
	public static int KeyType_End = 2;

	public static void deletAllFile(File dir,int keyType,String key)
	{
		Log.d(THIS_FILE, "deletAllFile dir = " + dir + " keyType = " + keyType + " key = " + key);
		if (dir == null
				|| dir.exists() == false)
		{
			Log.d(THIS_FILE, "deletAllFile !dir.exists()");
			return;
		}

		if (!dir.isDirectory())
		{
			Log.d(THIS_FILE, "deletAllFile !dir.isDirectory()");
			return;
		}
		File[] fileArr = dir.listFiles();
		if(fileArr == null
				|| fileArr.length <= 0)
		{
			Log.d(THIS_FILE, "deletAllFile fileArr.length <= 0");
			return;
		}
		for(int i = 0; i< fileArr.length; i ++)
		{
			File file = fileArr[i];
			String name = file.getName();
			if(keyType == KeyType_None)
			{
				Log.d(THIS_FILE, "deletAllFile file = " + file);
				file.delete();
			}
			else if(keyType == KeyType_Start
					&& name.startsWith(key))
			{
				Log.d(THIS_FILE, "deletAllFile file = " + file);
				file.delete();
			}
			else if(keyType == KeyType_End
					&& name.endsWith(key))
			{
				Log.d(THIS_FILE, "deletAllFile file = " + file);
				file.delete();
			}
		}
	}

	public static void saveImgFile(File file,Bitmap bitmap)
	{
		FileOutputStream b = null;
		try {
			b = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	private static final String File_Path = Environment.getExternalStorageDirectory() + File.separator + "CloudPTT" + File.separator ;// + "REC" + File.separator;
	public static String getFilePath(int type)
	{
		String path = File_Path + "SMS" + File.separator;
		if(type == SessionInfo.Filetype_Pic)
		{
			path = path + Common.getDate() + File.separator + "IMG" + File.separator;
		}
		else if(type == SessionInfo.Filetype_Voice)
		{
			path = path + Common.getDate() + File.separator + "IMG" + File.separator;
		}
		else if(type == SessionInfo.Filetype_Video)
		{
			path = path + Common.getDate() + File.separator + "IMG" + File.separator;
		}
		else//(type == SessionInfo.Filetype_File)
		{
			path = path + Common.getDate() + File.separator + "IMG" + File.separator;
		}
		return path;
	}

	public static String getConfigFilePath()
	{
		String path = File_Path + "config.ini";
		return path;
	}



	/**
	 * 压缩文件和文件夹
	 *
	 * @param srcFileString 要压缩的文件或文件夹
	 * @param zipFileString 压缩完成的Zip路径
	 * @throws Exception
	 */

	private int fileCount = 0;
	private int fileIndex = 0;
	public void zipFolder(String srcFileString, String zipFileString, ZipListener listener) throws Exception
	{
//创建ZIP
		ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream(zipFileString));
//创建文件
		File file = new File(srcFileString);
//压缩
		Log.debug(FileOperation.class,"ZipFolder file.getParent = "+file.getParent()+"file.getAbsolutePath = "+file.getAbsolutePath());
		zipFiles(file.getParent()+ File.separator, file.getName(), outZip,listener);
//完成和关闭
		outZip.finish();
		outZip.close();
	}

	/**
	 * 压缩文件
	 *
	 * @param folderString
	 * @param fileString
	 * @param zipOutputSteam
	 * @throws Exception
	 */

	private void zipFiles(String folderString, String fileString, ZipOutputStream zipOutputSteam,ZipListener listener) throws Exception
	{
		Log.debug(FileOperation.class,"ZipFiles folderString = "+folderString +"fileString = " + fileString);
		if (zipOutputSteam == null)
		{
			return;
		}
		File file = new File(folderString + fileString);
		if (file.isFile())
		{
			fileIndex ++;
			if(listener != null)
			{
				listener.onProcess(fileIndex,fileCount);
			}
			ZipEntry zipEntry = new ZipEntry(fileString);
			FileInputStream inputStream = new FileInputStream(file);
			zipOutputSteam.putNextEntry(zipEntry);
			int len;
			byte[] buffer = new byte[4096];
			while ((len = inputStream.read(buffer)) != -1)
			{
				zipOutputSteam.write(buffer, 0, len);
			}
			zipOutputSteam.closeEntry();
		}
		else
		{
//文件夹
			String fileList[] = file.list();
			fileCount = fileList.length;
			if(listener != null)
			{
				listener.onProcess(fileIndex,fileCount);
			}
//没有子文件和压缩
			if (fileList.length <= 0) {
				ZipEntry zipEntry = new ZipEntry(fileString + File.separator);
				zipOutputSteam.putNextEntry(zipEntry);
				zipOutputSteam.closeEntry();
			}
//子文件和递归
			for (int i = 0; i < fileList.length; i++)
			{
				zipFiles(folderString+fileString+"/", fileList[i], zipOutputSteam,listener);
			}
		}
	}
}
